package com.ruoyi.web.controller.inventory;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.inventory.domain.TSpPart;
import com.ruoyi.inventory.service.ITSpPartService;
import com.ruoyi.inventory.domain.dto.PartDTO;
import com.ruoyi.inventory.util.PartConverter;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 备件Controller
 *
 * @author ruoyi
 * @date 2025-09-26
 */
@RestController
@RequestMapping("/system/part")
public class TSpPartController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(TSpPartController.class);
    
    @Autowired
    private ITSpPartService tSpPartService;

    /**
     * 查询备件列表
     */
    @PreAuthorize("@ss.hasPermi('system:part:list')")
    @GetMapping("/list")
    public TableDataInfo list(TSpPart tSpPart)
    {
        startPage();
        List<TSpPart> list = tSpPartService.selectTSpPartList(tSpPart);
        return getDataTable(list);
    }

    /**
     * 查询备件列表(DTO)
     */
    @GetMapping("/list-dto")
    public AjaxResult listDTO(TSpPart tSpPart)
    {
        List<TSpPart> list = tSpPartService.selectTSpPartList(tSpPart);
        List<PartDTO> dtoList = PartConverter.toDTOList(list);
        return AjaxResult.success(dtoList);
    }

    /**
     * 导出备件列表
     */
    @PreAuthorize("@ss.hasPermi('system:part:export')")
    @Log(title = "备件", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TSpPart tSpPart)
    {
        List<TSpPart> list = tSpPartService.selectTSpPartList(tSpPart);
        ExcelUtil<TSpPart> util = new ExcelUtil<TSpPart>(TSpPart.class);
        util.exportExcel(response, list, "备件数据");
    }

    /**
     * 获取备件详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:part:query')")
    @GetMapping(value = "/{partNo}")
    public AjaxResult getInfo(@PathVariable("partNo") String partNo)
    {
        TSpPart part = tSpPartService.selectTSpPartByPartNo(partNo);
        PartDTO dto = PartConverter.toDTO(part);
        
        // 处理关联资产数据：将 JSON 字符串转换为 List<Object>
        if (dto.getAssociatedAssetsJson() != null && !dto.getAssociatedAssetsJson().trim().isEmpty()) {
            try {
                java.util.List<Object> assets = com.alibaba.fastjson2.JSON.parseArray(dto.getAssociatedAssetsJson(), Object.class);
                dto.setAssets(assets);
            } catch (Exception e) {
                // 如果反序列化失败，记录日志但不影响其他操作
                logger.warn("Failed to deserialize assets from JSON: {}", e.getMessage());
                dto.setAssets(new java.util.ArrayList<>());
            }
        } else {
            dto.setAssets(new java.util.ArrayList<>());
        }
        
        return success(dto);
    }

    /**
     * 新增备件
     */
    @PreAuthorize("@ss.hasPermi('system:part:add')")
    @Log(title = "备件", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PartDTO partDTO)
    {
        // 处理关联资产数据：将 List<Object> 转换为 JSON 字符串
        if (partDTO.getAssets() != null) {
            try {
                String assetsJson = com.alibaba.fastjson2.JSON.toJSONString(partDTO.getAssets());
                partDTO.setAssociatedAssetsJson(assetsJson);
                logger.info("Serialized assets to JSON: {}", assetsJson);
            } catch (Exception e) {
                // 如果序列化失败，记录日志但不影响其他操作
                logger.warn("Failed to serialize assets to JSON: {}", e.getMessage());
            }
        } else {
            logger.info("No assets to serialize, assets is null");
        }
        
        TSpPart tSpPart = PartConverter.toEntity(partDTO);
        logger.info("TSpPart associatedAssetsJson: {}", tSpPart.getAssociatedAssetsJson());
        return toAjax(tSpPartService.insertTSpPart(tSpPart));
    }

    /**
     * 修改备件
     */
    @PreAuthorize("@ss.hasPermi('system:part:edit')")
    @Log(title = "备件", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PartDTO partDTO)
    {
        // 处理关联资产数据：将 List<Object> 转换为 JSON 字符串
        if (partDTO.getAssets() != null) {
            try {
                String assetsJson = com.alibaba.fastjson2.JSON.toJSONString(partDTO.getAssets());
                partDTO.setAssociatedAssetsJson(assetsJson);
                logger.info("Serialized assets to JSON: {}", assetsJson);
            } catch (Exception e) {
                // 如果序列化失败，记录日志但不影响其他操作
                logger.warn("Failed to serialize assets to JSON: {}", e.getMessage());
            }
        } else {
            logger.info("No assets to serialize, assets is null");
        }
        
        TSpPart tSpPart = PartConverter.toEntity(partDTO);
        logger.info("TSpPart associatedAssetsJson: {}", tSpPart.getAssociatedAssetsJson());
        return toAjax(tSpPartService.updateTSpPart(tSpPart));
    }

    /**
     * 删除备件
     */
    @PreAuthorize("@ss.hasPermi('system:part:remove')")
    @Log(title = "备件", businessType = BusinessType.DELETE)
    @DeleteMapping("/{partNos}")
    public AjaxResult remove(@PathVariable String[] partNos)
    {
        return toAjax(tSpPartService.deleteTSpPartByPartNos(partNos));
    }
}
